package cn.mastor.controller;

import cn.mastor.domain.Dynami;
import cn.mastor.query.DynamiQuery;
import cn.mastor.service.IDynamiService;
import com.baomidou.mybatisplus.plugins.Page;
import mihoyo.result.JSONResult;
import mihoyo.result.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/dynami")
public class DynamiController {

    @Autowired
    public IDynamiService dynamiService;


    /**
    * 保存和修改公用的
    */
    @RequestMapping(value="/save",method= RequestMethod.POST)
    public JSONResult saveOrUpdate(@RequestBody Dynami dynami){
        if(dynami.getId()!=null){
            dynamiService.updateById(dynami);
        }else{
            dynamiService.insert(dynami);
        }
        return JSONResult.success();
    }


    /**
     * 查询指定用户动态
     */
    @RequestMapping(value="/dynami/{id}",method=RequestMethod.GET)
    public JSONResult selectDynamicById(@PathVariable("id") Integer id){
        List<Dynami> dynamis = dynamiService.selectDynamicById(id);
        dynamis.sort(new Comparator<Dynami>() {
            @Override
            public int compare(Dynami o1, Dynami o2) {
                return (int) (o2.getTime().getTime()-o1.getTime().getTime());
            }
        });
        return JSONResult.success(dynamis);
    }
    /**
    * 删除对象
    */
    @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
    public JSONResult delete(@PathVariable("id") Long id){
        dynamiService.deleteById(id);
        return JSONResult.success();
    }

    /**
   * 获取对象
   */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public JSONResult get(@PathVariable("id")Long id){
        return JSONResult.success(dynamiService.selectById(id));
    }



    /**
    * 查询所有对象
    */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public JSONResult list(){
        return JSONResult.success(dynamiService.selectList(null));
    }


    /**
    * 带条件分页查询数据
    */
    @RequestMapping(value = "/pagelist",method = RequestMethod.POST)
    public JSONResult page(@RequestBody DynamiQuery query){
        Page<Dynami> page = new Page<Dynami>(query.getPage(),query.getRows());
        page = dynamiService.selectPage(page);
        return JSONResult.success(new PageList<Dynami>(page.getTotal(),page.getRecords()));
    }
}
